//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.UserCardMapper;
import com.wsd.smartcarwasher.domain.Card;
import com.wsd.smartcarwasher.domain.CardOrder;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.CommonUtil;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Api(
        tags = {"用户会员卡购买订单相关接口"}
)
@Controller
@CrossOrigin
public class CardOrderController {
    @Autowired(required = false)
    private CardOrderService cardOrderService;
    @Resource
    private WxService wxService;
    @Resource
    private CardService cardService;
    @Resource
    private WxPayService wxPayService;
    @Resource
    private UserCardMapper userCardMapper;

    @Resource
    private UserInfoService userInfoService;

    public CardOrderController() {
    }

    @Log("购买了会员卡")
    @ApiOperation(
            value = "购买会员卡信息",
            notes = "小程序创建会员卡购买订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "cardId",
            value = "要购买的会员卡id",
            required = true,
            dataType = "Integer"
    )
    @RequestMapping(
            value = {"v1/card_order"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createOrder(@RequestParam("cardId") int cardId, HttpServletRequest request) {
        //System.out.println("创建会员卡订单成功");
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        } else {
            Card card = this.cardService.queryCardByCardId(cardId);
            if (card == null) {
                return ReturnUtil.Error(ResultState.NO_CARD.getMsg());
            } else {
                CardOrder cardOrder = new CardOrder(card);
                cardOrder.setUserId(String.valueOf(user.getUserId()));
                int changeRow = this.cardOrderService.addCardOrder(cardOrder);
                //System.out.println("添加会员卡订单成功");
                if (changeRow == 0) {
                    return ReturnUtil.Error(ResultState.ORDER_CREATE_FAIL.getMsg());
                } else {
                    if (BigDecimal.ZERO.compareTo(cardOrder.getPayPrice()) >= 0) {

                        this.cardOrderService.payFinishOrder(cardOrder);
                        ReturnUtil.Success(ResultState.ORDER_PAY_SUCCEED.getMsg(), cardOrder);
                    }
                    String clientIP = CommonUtil.getClientIp(request);
                    return this.wxPayService.payByWx(user.getOpenid(), clientIP, cardOrder);
                }
            }
        }
    }


    @Log("购买会员卡信息")
    @ApiOperation(
            value = "新更改==>购买会员卡信息",
            notes = "新更改==>小程序创建会员卡购买订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "cardId",
            value = "新更改==>要购买的会员卡id",
            required = true,
            dataType = "Integer"
    )
    @RequestMapping(
            value = {"v1/new/card_order"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createNewOrder(@RequestParam("cardId") int cardId, HttpServletRequest request) {
//        System.out.println("创建会员卡订单成功");

        String sessionId = request.getHeader("authorization");
        String orderSn=null;
        String timeStamp=null;
        Map<String,Object> map=new HashMap<>();
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        } else {
            Card card = this.cardService.queryCardByCardId(cardId);
            if (card == null) {
                return ReturnUtil.Error(ResultState.NO_CARD_ORDER.getMsg());
            } else {
                //根据cardId去查询该会员卡是否已经为用户拥有
//                List<UserCard> userCards=this.userCardMapper.userCardListBybelong(cardId,user.getUserId());
//                if(request.getSession().getAttribute("cardBelong"+user.getUserId())==null)
//                {
//                    if(!userCards.isEmpty())
//                    {
//                        request.getSession().setAttribute("cardBelong"+user.getUserId()," ");
//                        return ReturnUtil.Error(ResultState.OWNED_CARD.getMsg());
//                    }
//                }else{
//                    request.removeAttribute("cardBelong"+user.getUserId());
//                }
                CardOrder cardOrder = new CardOrder(card);
                cardOrder.setUserId(String.valueOf(user.getUserId()));
                int changeRow = this.cardOrderService.addCardOrder(cardOrder);
//                System.out.println("添加会员卡订单成功");
                orderSn=cardOrder.getOrderSn();
                map.put("orderSn",orderSn);
                timeStamp=DateUtil.format(cardOrder.getCreateTime(),"yyyy-MM-dd HH:mm:ss");
                map.put("timeStamp",timeStamp);
                if (changeRow == 0) {
                    return ReturnUtil.Error(ResultState.ORDER_CREATE_FAIL.getMsg());
                }
                else {
                    if (BigDecimal.ZERO.compareTo(cardOrder.getPayPrice()) >= 0) {

                        this.cardOrderService.payFinishOrder(cardOrder);
                        ReturnUtil.Success(ResultState.ORDER_PAY_SUCCEED.getMsg(), cardOrder);
                    }
//                    String clientIP = CommonUtil.getClientIp(request);
//                    return this.wxPayService.payByWx(user.getOpenid(), clientIP, cardOrder);
                }
            }
        }

        return  ReturnUtil.Success(ResultState.ORDER_CREATE_SUCCESS.getMsg(),map);
    }


    /**
     * 创建微信官方预支付订单信息
     * @param orderSn
     * @param request
     * @return
     */
    @ApiOperation(
            value = "新更改==>创建会员卡购买微信官方预支付订单信息",
            notes = "新更改==>创建会员卡购买微信官方预支付订单信息",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "orderSn",
            value = "新更改==>要购买的会员卡id",
            required = true,
            dataType = "Integer"
    )
    @RequestMapping(
            value = {"v1/new/card_order/pay"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createNewOrderPay(@RequestParam("orderSn") String orderSn, HttpServletRequest request) {
//        System.out.println("创建会员卡订单成功");
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        } else {
            //如果订单中的userId与当前用户的userId不符，则认定该会员卡订单将由朋友代为支付
            CardOrder cardOrder=this.cardOrderService.queryOrderInfoByOrderSn(orderSn);

            if (cardOrder == null) {
                return ReturnUtil.Error(ResultState.NO_CARD_ORDER.getMsg());
            } else {
                if(cardOrder.getPayStatus()==2)
                {
                    return ReturnUtil.Error("该订单已被支付");
                }
                if(cardOrder.getHeuserId()!=null)
                {
                    return ReturnUtil.Error("该订单正在被其他朋友代付中...");
                }
                if(!user.getUserId().equals(cardOrder.getUserId()))
                {
                    cardOrder.setIsHepaid(1);
                    cardOrder.setHeuserId(user.getUserId());
                    this.cardOrderService.updateCardOrder(cardOrder);
                }
                String clientIP = CommonUtil.getClientIp(request);
               return this.wxPayService.payByWx(user.getOpenid(), clientIP, cardOrder);
            }
        }

    }
    @Log("代付了会员卡")
    @ApiOperation(
            value = "小程序新增==>朋友代付购买会员卡信息",
            notes = "小程序创建会员卡购买订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "ucId",
            value = "会员卡订单对应的ucId",
            required = true,
            dataType = "Integer"
    )
    @RequestMapping(
            value = {"v1/card_order_hepaid"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createHePaidOrder(HttpServletRequest request,@RequestParam("ucId") String ucId) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }else{
            CardOrder cardOrder = this.cardService.queryCardOrder(ucId);
            if (cardOrder == null) {
                return ReturnUtil.Error(ResultState.NO_CARD.getMsg());
            } else {
                    if(cardOrder.getPayStatus()==2)
                    {
                        ReturnUtil.Error(ResultState.ORDER_HE_PAY_SUCCEED.getMsg());
                    }
                    if (BigDecimal.ZERO.compareTo(cardOrder.getPayPrice()) >= 0) {
                        this.cardOrderService.payFinishOrder(cardOrder);
                        ReturnUtil.Success(ResultState.ORDER_PAY_SUCCEED.getMsg(), cardOrder);
                    }
                    String clientIP = CommonUtil.getClientIp(request);
                    return this.wxPayService.friendPayByWx(user.getOpenid(), clientIP, cardOrder,user,ucId);
                }
            }
        }
    @ApiOperation(
            value = "小程序-查询用户购买会员卡的订单",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/user_card_order"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap createOrder(HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        return user == null ? ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg()) : ReturnUtil.Success(ResultState.QUERY_USER_CARD_ORDERS_SUCCESS.getMsg(), this.cardOrderService.queryUserOrder(user.getUserId()));
    }



    @ApiOperation(
            value = "(新增)小程序-根据orderSn查询会员卡订单详情",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/card_order_info"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap cardOrderInfo(@RequestParam(value = "orderSn") String orderSn,HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
//        UserInfo user=this.userInfoService.findByMobile("17791961563");
        return user == null ? ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg()) : ReturnUtil.Success(ResultState.QUERY_USER_CARD_ORDERS_SUCCESS.getMsg(), this.cardOrderService.queryOrderandCardInfoByOrderSn(orderSn));
    }

    @ApiOperation(
            value = "pc-查询用户购买会员卡的订单",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/getUserInfoCardOrder"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getUserInfoCardOrder(@RequestParam @ApiParam String userId,HttpServletRequest request) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        return ReturnUtil.Success(ResultState.QUERY_USER_CARD_ORDERS_SUCCESS.getMsg(), this.cardOrderService.queryUserOrder(userId));
    }

    @ApiOperation(
            value = "pc-查询所有用户购买会员卡的订单",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({
            @ApiImplicitParam(  name = "mobile", value = "187029999212", required = false,  dataType = "String"),
            @ApiImplicitParam(  name = "time", value = "2020-01-20", required = false,  dataType = "String"),
            @ApiImplicitParam(  name = "orderSn", value = "12131ioonn23kn4k2n4", required = false,  dataType = "String"),
    })
    @RequestMapping(
            value = {"v1/get_card_order"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap get_card_order(@RequestParam int Page,@RequestParam int PageSize,HttpServletRequest request) {

        String mobile = request.getParameter("mobile");
        String time = request.getParameter("time");
        String orderCode = request.getParameter("orderSn");

        CardOrder cardOrder = new CardOrder();
        if(null!=orderCode) {
            cardOrder.setOrderSn(orderCode);
        }
        if(null!=mobile) {
            cardOrder.setMobile(mobile);
        }
        if(null!=time) {
            cardOrder.setPayTime(DateUtil.convertStringToDate(time));
        }

        //String sessionId = request.getHeader("authorization");
        //UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        return ReturnUtil.Success(ResultState.QUERY_USER_CARD_ORDERS_SUCCESS.getMsg(), this.cardOrderService.queryUserOrderAll(Page,PageSize,cardOrder));
    }


    @ApiOperation(
            value = "pc端-刪除訂單",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/userCard/deleteByOrderSn"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap deleteByOrderSn(@RequestParam String orderSn) {

        int rows=this.cardOrderService.deleteCardOrder(orderSn);
        if(rows>0){
           return  ReturnUtil.Success("刪除成功");
        }

        return ReturnUtil.Error("刪除失敗");
    }



    @ApiOperation(
            value = "小程序-刪除用户会员卡訂單",
            notes = "用户订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/userCard/deleteCardByOrderSn"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap deleteCardByOrderSn(HttpServletRequest request,@RequestParam String orderSn) {
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if(user == null)
        {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        int rows=this.cardOrderService.deleteCardOrder(orderSn);
        if(rows>0){
            return  ReturnUtil.Success("刪除成功");
        }

        return ReturnUtil.Error("刪除失敗");
    }



    @ApiOperation(
            value = "小程序-用户拒绝下单，小程序返回订单号和状态",
            notes = "解锁订单",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"v1/cardOrder/UnlockCardOrder"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap unlockCardOrder(@RequestParam String orderSn,@RequestParam int payStatus) {
        CardOrder cardOrder=this.cardOrderService.queryOrderInfoByOrderSn(orderSn);
        if(cardOrder==null)
        {
            return  ReturnUtil.Error("该订单已失效");
        }
        if(cardOrder.getHeuserId()!=null&&cardOrder.getIsHepaid()!=0)
        {
            if(payStatus!=2)
            {
                //没有支付，解锁订单，让其他人购买
                cardOrder.setHeuserId(null);
                cardOrder.setIsHepaid(0);
                cardOrder.setOrderStatus(100);
                this.cardOrderService.updateCardOrder(cardOrder);
            }
        }
        
        return ReturnUtil.Success("订单重新激活成功，现为可购买状态");
    }

}
